package cn.qingfeng.a003_chat_v2.server.handler;

import cn.qingfeng.a003_chat_v2.message.GcreateRequestMessage;
import cn.qingfeng.a003_chat_v2.server.groupsession.Group;
import cn.qingfeng.a003_chat_v2.server.groupsession.GroupSession;
import cn.qingfeng.a003_chat_v2.server.groupsession.GroupSessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@ChannelHandler.Sharable
public class GcreateHandler extends SimpleChannelInboundHandler<GcreateRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GcreateRequestMessage msg) throws Exception {
        final GroupSession groupSession = GroupSessionFactory.getSession();

        if (msg == null) {
            return;
        }

        String username = msg.getFromUsername();
        String groupName = msg.getGroupName();
        List<String> memberlist = msg.getMembers();
        Set<String> memberSet = new HashSet<>(memberlist);
        Group group = groupSession.createGroup(groupName, memberSet);
        if (group == null) {
            ctx.writeAndFlush(groupName + " 创建成功！");
            List<Channel> membersChannel = groupSession.getMembersChannel(groupName);
            for (Channel channel : membersChannel) {
                channel.writeAndFlush("您已被" + username + "拉入群：" + groupName);
            }
        } else {
            ctx.writeAndFlush("群已存在，请更改群名重试！");
        }
    }
}